# JSON Tree

## Overview


> Image: Illustration of the JSON Tree component displaying structured data in a collapsible tree format.


## When to use this component
- To display structured data in a collapsible tree format. 

## When to use another component
- For displaying pieces of code, command-line instructions, or technical values that need to be visually distinguished from surrounding content, consider using `Code`.

### Check out:
- [Code][1]

## Behaviors

### Data types
- Values are visually distinguished by their data type (e.g., string, number, boolean, null, object, array).

> Image: A display of a JSON object showing various data types like numbers, strings, booleans, null, and nested objects/arrays, with different colors indicating types.


### Expanding content
- Users can expand and collapse individual nodes (objects or arrays) to reveal or hide their contents. You can set the `defaultExpanded` prop to have it expanded by default.

> Image: A display illustrating the expandable and collapsible nature of a JSON tree, showing a collapsed object on the left and its expanded view revealing nested structures on the right.


### Expand all
- `Shift + Click` or `Shift + Enter` to expand all child nodes at once.

## Usage
- The JSON Tree component accepts a JSON object or array as its primary data input.

## Content
- Use proper syntax and indentation to ensure readability and clarity.

[1]: ./Code

## Examples


### obj

```typescript
import React from 'react';

import JSONTree from '@splunk/react-ui/JSONTree';

const obj = {
    menu: {
        id: 8989,
        value: 'File',
        property: {},
        items: [],
        popup: {
            menuitem: [
                {
                    value: 'New',
                    onclick: 'CreateNewDoc()',
                },
                {
                    value: null,
                    onclick: false,
                },
                {
                    value: 'Close',
                    onclick: 'CloseDoc()',
                },
            ],
        },
    },
};


export default function Basic() {
    return <JSONTree json={obj} defaultExpanded />;
}
```



### Expand Children On Shift Key

```typescript
import React from 'react';

import JSONTree from '@splunk/react-ui/JSONTree';

const obj = {
    menu: {
        id: 8989,
        value: 'File',
        property: {},
        items: [],
        popup: {
            menuitem: [
                {
                    value: 'New',
                    onclick: 'CreateNewDoc()',
                },
                {
                    value: null,
                    onclick: false,
                },
                {
                    value: 'Close',
                    onclick: 'CloseDoc()',
                },
            ],
        },
    },
};


export default function ExpandChildrenOnShiftKey() {
    return <JSONTree json={obj} expandChildrenOnShiftKey />;
}
```



### Click Events

```typescript
import React, { Component } from 'react';

import DL, { Term as DT, Description as DD } from '@splunk/react-ui/DefinitionList';
import JSONTree, {
    JSONTreeClickValueHandler,
    JSONTreeClickKeyHandler,
} from '@splunk/react-ui/JSONTree';
import P from '@splunk/react-ui/Paragraph';

const json = {
    glossary: {
        title: 'example glossary',
        description: [],
        GlossDiv: {
            title: 'S',
            GlossList: {
                GlossEntry: {
                    ID: 'SGML',
                    SortAs: 'SGML',
                    GlossTerm: 'Standard Generalized Markup Language',
                    Acronym: 'SGML',
                    Abbrev: 'ISO 8879:1986',
                    GlossDef: {
                        para: 'Used to create markup languages such as DocBook.',
                        GlossSeeAlso: ['GML', null, 1, true],
                    },
                    GlossSee: {},
                },
            },
        },
    },
};


class Events extends Component<
    object,
    { key: string; keyPath?: (string | number)[]; value: string }
> {
    constructor(props: object) {
        super(props);
        this.state = {
            key: '',
            value: '',
        };
    }

    onClickJSONValue: JSONTreeClickValueHandler = (e, { key, keyPath, value }) => {
        this.setState({ key, keyPath, value });
    };

    onClickJSONKey: JSONTreeClickKeyHandler = (e, { key, keyPath }) => {
        this.setState({ key, keyPath, value: '' });
    };

    render() {
        const { key, keyPath, value } = this.state;

        return (
            <div>
                <JSONTree
                    json={json}
                    onClickValue={this.onClickJSONValue}
                    onClickKey={this.onClickJSONKey}
                />
                <aside style={{ marginTop: 20 }} aria-live="polite" aria-relevant="text">
                    <P>Click a key or value to see the returned data</P>
                    <DL>
                        {value ? (
                            <div style={{ overflow: 'scroll' }}>
                                <DT>Clicked value:</DT>
                                <DD>
                                    <code>{value}</code>
                                </DD>
                            </div>
                        ) : null}
                        {key ? (
                            <div style={{ overflow: 'scroll', marginBottom: 10 }}>
                                <DT>With key:</DT>
                                <DD>
                                    <code>{key}</code>
                                </DD>
                                <DT>With keyPath:</DT>
                                <DD>
                                    <code>{keyPath !== undefined && `[${keyPath}]`}</code>
                                </DD>
                            </div>
                        ) : null}
                    </DL>
                </aside>
            </div>
        );
    }
}

export default Events;
```




## API


### JSONTree API

Used to visualize a JSON string.

#### Props

| Name | Type | Required | Default | Description |
|------|------|------|------|------|
| defaultExpanded | boolean | no | false | If set to `true`, `defaultExpanded` will expand all nodes on initial render. The default is `false`, which expands only the first level of properties. |
| elementRef | React.Ref<HTMLElement> | no |  | A React ref which is set to the DOM element when the component mounts and null when it unmounts. |
| expandChildrenOnShiftKey | boolean | no | true | If set to `true`, using `shift + click` or `shift + enter` will expand all descendant nodes of the tree at once. A tooltip is added to the expand all / collapse all button to indicate that this feature is enabled. Defaults to `true`. |
| indent | number | no | 4 | Number of space characters per level of indentation. |
| json | string \| JSONElement | yes |  | The JSON string to visualize. Alternatively, this prop also accepts objects and other possible return types of `JSON.parse`. `JSONTree` doesn't perform any runtime type validation. If the passed value contains circular dependencies or types not representable in JSON like functions and symbols, the component behavior is unspecified. |
| onClickKey | JSONTreeClickKeyHandler | no |  | Optional event handler to call if keys are clicked on. The function signature is `onClickKey({path, keyPath, value})`, where `path` is the property path , `.a.b`; and keyPath is an array of that property path, `['a', 'b']. |
| onClickValue | JSONTreeClickValueHandler | no |  | Optional event handler to call if values are clicked on. The function signature is `onClickValue({path, keyPath, value})`, where `path` is the property path , `.a.b`; keyPath is an array of that property path, `['a', 'b']; and `value` is the value that was clicked. |
| overflow | 'wrap' \| 'scroll' | no | 'scroll' | Handles overflow by wrapping values or by enabling scrolling. |

#### Types

| Name | Type | Description |
|------|------|------|
| JSONElement | string \| { [x: string]: JSONElement } \| number \| boolean \| null \| JSONElement[] |  |
| JSONTreeClickKeyHandler | (     event: React.MouseEvent<HTMLButtonElement>,     data: {         key: string;         keyPath: (string \| number)[];     } ) => void |  |
| JSONTreeClickValueHandler | (     event: React.MouseEvent<HTMLButtonElement>,     data: {         key: string;         keyPath: (string \| number)[];         value: string;     } ) => void |  |





